package controller;

import config.Interceptor.PassToken;
import config.Interceptor.Role;
import entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import service.impl.Userserviceimpl;
import utils.CommonRetumType;
import utils.RedisUtil;
import utils.error.BusinessException;
import utils.error.EmBusinessError;

@RestController
@RequestMapping("/user")
public class Usercontroller extends BaseController {
    @Autowired
    private Userserviceimpl userserviceimpl;
    @Autowired
    private RedisUtil redisUtil;

    @GetMapping("/findall")
    @Role
    public CommonRetumType listindex()
    {
        Object users = userserviceimpl.findall();
        return CommonRetumType.create(users,"数据查询成功");
    }

    @GetMapping("/findid")
    @PassToken
    public CommonRetumType findid(@RequestParam("id") Integer id) throws BusinessException {
        User user = userserviceimpl.findeid(id);
        if (user == null)
        {
            throw new BusinessException(EmBusinessError.USER_NOT_EXIST);
        }else {
            Object user1 = redisUtil.get("user");
            if (user1 == null)
            {
                redisUtil.set("user",user);
            }else {
                System.out.println("缓存查询中.....");
            }

            return CommonRetumType.create(user,"数据查询成功");
        }
    }

    //    用户添加
    @GetMapping("/create")
    @PassToken
    public CommonRetumType create(User user) throws BusinessException {
        Integer user1 = userserviceimpl.insert(user);
        return CommonRetumType.create(user1,"创建成功");
    }


    // 指定用户id更新
    @PutMapping("/update")
    public CommonRetumType update(User user) throws BusinessException {
        Integer userupdate = userserviceimpl.updateByPrimaryKeySelective(user);
        return CommonRetumType.create(userupdate,"数据更新成功");

    }
    //    删除用户
    @DeleteMapping("/delete")
    @Role
    public CommonRetumType delete(@RequestParam("id") Integer id)
    {
        Integer userdelete = userserviceimpl.deleteByPrimaryKey(id);
        return CommonRetumType.create(userdelete,"删除成功");
    }

}
